package com.ti.demo.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ti.demo.entity.CityRequest;
import com.ti.demo.entity.WeatherInfo;
import com.ti.demo.entity.WeatherRequest;
import com.ti.demo.entity.WeatherResponse;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;

/**
 * @description: com.ti.demo.service
 * @Author Triagen
 * @Date 2025/10/10 17:03
 */
@Service
public class WeatherService {

    @Autowired
    private RestClient restClient;

    @Tool(description = "get weather info by cityId")
    public WeatherInfo getWeatherInfo(WeatherRequest weatherRequest) {
        WeatherResponse weatherResponse = restClient.get().uri("/now/" + weatherRequest.getCityId()).retrieve().body(WeatherResponse.class);
        return weatherResponse.getData();
    }

    @Tool(description = "To get weather info, we need to use cityId, this tool is used to get cityId from cityName")
    public String getCityId(CityRequest cityRequest) {
        String body = restClient.get().uri("/map/weather/1").retrieve().body(String.class);
        JSONObject jsonObject = JSON.parseObject(body);
        return jsonObject.getJSONObject("data").getJSONArray("city").stream()
                .filter(o -> cityRequest.getCityName().equals(((JSONArray) o).getString(1)))
                .findFirst()
                .map(o -> ((JSONArray) o).getString(0))
                .get();
    }
}
